package com.study.interceptor;

import com.study.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 *
 * 拦截器Inceptor：是一种动态拦截方法调用的机制，类似于过滤器，SPRING框架提供，主要用来动态拦截控制器方法的执行（Controller层）
 * 作用：拦截请求，在指定的方法调用前后，根据业务需要执行预先设定的代码
 *
 * 记得还要注册拦截器！！
 *
 * Filter与Inceptor区别
 * 接口规范不同：过滤器实现Filter接口，拦截器需要实现HandlerInceptor接口
 * 拦截范围不同：filter会拦截所有资源，而Interceptor只拦截Spring环境中的资源
 *
 */
@Component
public class LoginInterctptor implements HandlerInterceptor {
    @Override//目标资源方法执行前执行，返回true放行；否则不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        if(url.contains("login")) {
            return true;
        }
        String jwt = request.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    @Override//目标资源方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle............................");
    }

    @Override//最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after...............................");
    }

}
